package com.xin.usermanagebackend.aop;

import com.xin.usermanagebackend.annotation.AuthCheck;
import com.xin.usermanagebackend.constant.ResultCode;
import com.xin.usermanagebackend.constant.UserConstant;
import com.xin.usermanagebackend.exception.BusinessException;
import com.xin.usermanagebackend.model.enums.UserRoleEnum;
import com.xin.usermanagebackend.model.vo.UserVo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
public class AuthInterceptor {
    /**
     * 如果是user权限，user和admin都有权限
     * 如果是admin权限 必须是admin
     * @param proceedingJoinPoint
     * @param authCheck
     * @return
     * @throws Throwable
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint proceedingJoinPoint, AuthCheck authCheck) throws Throwable {
        String mustoRole = authCheck.mustoRole();
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        UserVo userVo =(UserVo) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (userVo==null){
            throw new BusinessException(ResultCode.SYSTEM_ERROR,"未登录");
        }
        String userRole = userVo.getUserRole();
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(mustoRole);
        if (userRoleEnum==null){
            throw new BusinessException(ResultCode.PARAM_ERROR,"没有这种角色");
        }
        if (userRoleEnum.value.equals("user")){
            return proceedingJoinPoint.proceed();
        }
        if(!userRoleEnum.value.equals(userRole)){
            throw new BusinessException(ResultCode.SYSTEM_ERROR,"无权限");
        }
        return proceedingJoinPoint.proceed();
    }
}
